import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationfrom IPython.display import HTML# Set up the figure, the axis, and the plot elementsfig, axs = plt.subplots(3, 1, figsize=(7, 8))fig.tight_layout(pad=3.0)N =10000# size of the populationn =10# sample sizeK =1000# number of times to sample# Create the source distribution: Here I'm using a normal distribution for simplicitymu =10# meansigma =1# standard deviationsource_data = np.random.normal(mu, sigma, N)sample_means = []def update(num):# Clear the previous histogramsfor ax in axs: ax.cla() x_min =min(source_data) -1 x_max =max(source_data) +1# First panel: the population histogram axs[0].hist(source_data, bins=50, color='blue', alpha=0.7) axs[0].set_title("Source Distribution") axs[0].set_xlim(x_min, x_max) axs[0].text(x_max -0.1* (x_max - x_min), 0.8* N/50, 'Mean: {:.2f}\nStd: {:.2f}'.format(np.mean(source_data), np.std(source_data)), va="top", ha="right")# Second panel: sample histogram sample = np.random.choice(source_data, n) axs[1].hist(sample, bins=50, color='green', alpha=0.7) axs[1].set_title("Sample of Size {}".format(n)) axs[1].set_xlim(x_min, x_max) axs[1].set_ylim(0, 15) axs[1].text(x_max -0.1* (x_max - x_min), 15*0.2666, 'Mean: {:.2f}\nStd: {:.2f}'.format(np.mean(sample), np.std(sample)), va="top", ha="right")# Third panel: sample mean histogram# Add the mean of the current sample to sample_means sample_means.append(np.mean(sample)) axs[2].hist(sample_means, bins=50, color='red', alpha=0.7) axs[2].set_title("Distribution of Sample Means (n={})".format(n)) axs[2].set_xlim(x_min, x_max) axs[2].set_ylim(0, 30) axs[2].text(x_max -0.1* (x_max - x_min), 30*0.2666, 'Mean: {:.2f}\nStd: {:.2f}'.format(np.mean(sample_means), np.std(sample_means)), va="top", ha="right") plt.draw()ani = animation.FuncAnimation(fig, update, frames=K, repeat=False)# Display the animation in the Jupyter NotebookHTML(ani.to_jshtml())
Animation size has reached 20986142 bytes, exceeding the limit of 20971520.0. If you're sure you want a larger animation embedded, set the animation.embed_limit rc parameter to a larger value (in MB). This and further frames will be dropped.